package cn.kogee.controller;

import cn.kogee.domian.Product;
import cn.kogee.domian.Store;
import cn.kogee.feignclient.ProductFeign;
import cn.kogee.service.IProductService;
import cn.kogee.util.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
public class Productcontroller {
    @Autowired
    private ProductFeign productFeign;
    @Autowired
    private IProductService productService;
    @PutMapping
    public AjaxResult add(@RequestBody Product product){
        try {
            Product productdb = productService.findByNameorPrice(product.getName(),product.getPrice());
            if(productdb==null){
                productService.add(product);
                Store store = new Store();
                store.setProduct_id(product.getId());
                store.setNumber(product.getNumber());
                productFeign.addOrUpdate(store);
            }else {
                Store sto = productFeign.loadByProId(productdb.getId());
                sto.setNumber(sto.getNumber()+1);
                productFeign.addOrUpdate(sto);
            }
            return new AjaxResult();
        }catch (Exception e){
            e.printStackTrace();
            return new AjaxResult().setSuccess(false).setMsg("添加失败");
        }
    }
    @GetMapping("/{id}")
    public Product findById(@PathVariable("id") Long id){

        return productService.findById(id);
    }
    @PutMapping("/up")
    public Object upstore(@RequestBody Store store){
        return productFeign.addOrUpdate(store);
    }
    @GetMapping("/sto/{id}")
    public Object getSto(@PathVariable("id") Long id){
        return productFeign.loadById(id);
    }
}
